package com.sto.stoapp.activity.aviation;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.RouteManager;
import com.sto.stoapp.db.manager.SiteFullManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.entity.RouteEntity;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.BlueWeigthManager;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.scan.ScanRuleManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BlueReadThread;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import sto.android.app.StoPdaKeyEvent;

/**
 * 装包&发件
 * 
 * @author mgf
 * 
 */
@SuppressLint("HandlerLeak")
public class StoBagAndSendActivity extends StoListenerActivity {

	private StoHhmEditText route;
	private StoHhmEditText nextStation;
	private StoHhmEditText centerDes;
	private StoHhmEditText carID;
	private StoHhmEditText bagCode;
	// private StoHhmEditText code;
	private RadioButton goods, notgoods;
	private DataBusinessEntity dataBusiness;

	// private List<EditText> edit = new ArrayList<EditText>();

	private int itemType = 1;
	// 车辆ID必须是6位
	// private int CARID_LENGTH = 6;
	// 路由长度8位
	// private int ROUTE_LENGTH = 8;

	private String nextStationCode = "";
	private String nextStationName = "";
	// 路由号
	private String routeCode = "";
	// 二级中转目的地
	private String centerDesCode = "";
	private String centerDesName = "";
	// 24小时上传到服务器需要做一个区分，用1表示
	private boolean IS_24HOURS = false;
	private static final String A = "A";// 1 0
	private static final String B = "B";// 0

	private String billNo="";

	private BaseDialog filterDialog=null;

	private float blueWeight = -1;

	private TextView weight;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_avi_bag_and_send_piece);
		this.setTitleBottom(R.string.bag_and_send_piece,
				HomeBroadAction.AVIATION_SCANNER_BROAD);
		IS_24HOURS = this.getIntent().getBooleanExtra(
				UnifiedStaticType.IS_24HOURS, false);
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		initScanRecordAdapter(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_PACKET_SEND);
		bluetoothConnect();
	}

	/*
	 * 初始化控件
	 */
	private void initWidget() {
		route = (StoHhmEditText) findViewById(R.id.avi_route_number);
		nextStation = (StoHhmEditText) this.findViewById(R.id.avi_next_station);
		centerDes = (StoHhmEditText) findViewById(R.id.avi_destination);
		carID = (StoHhmEditText) this.findViewById(R.id.avi_carID);
		bagCode = (StoHhmEditText) this.findViewById(R.id.avi_bag_code);
		code = (StoHhmEditText) this.findViewById(R.id.avi_odd_numbers_text);
		goods = (RadioButton) this.findViewById(R.id.avi_goods_sample);
		notgoods = (RadioButton) this.findViewById(R.id.avi_no_goods_sample);
		weight = (TextView) this.findViewById(R.id.enter_count);
		addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_PACKET_SEND);
		addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_PACKAGE_OPERATE);
	}

	@Override
	protected void onDestroy() {
		bluetoothHandler.removeMessages(BlueWeigthManager.UPDATE_BLUE_DATA);
		super.onDestroy();
	}

	// 处理扫描数据
	@SuppressLint("NewApi")
	private void processScanData() {
		try {

			if (!weight.getText().toString().isEmpty() && blueWeight <= 0) {
				Helper.showSoundToast(this, getString(R.string.no_weight_data),
						false);
				return;
			}

			if (route.getText().toString().length() <= 0) {
				Helper.showSoundToast(this, getString(R.string.route_is_empty),
						false);
				route.requestFocus();
				return;
			} else {
				if (nextStationCode.length() <= 0
						|| centerDesCode.length() <= 0) {
					Helper.showSoundToast(this,
							getString(R.string.route_is_undefined), false);
					route.setText("");
					route.requestFocus();
					return;
				}
			}
			if (!checkCarId()) {
				return;
			}
			if (!checkBagCode()) {
				return;
			}
			if ((bagCode.getText().toString().trim()).equals(code.getText()
					.toString().trim())) {
				Helper.showSoundToast(this, "袋号重复", false);
				code.requestFocus();
				code.setText("");
				return;
			}

			billNo=code.getText().toString();
			float maxWeight=StoFilePreference.getInstance(this).getBlueWeight();

			if(blueWeight>maxWeight){
				ScanOff();
				filterDialog=new BaseDialog(this);
				filterDialog.setTitles("重量限制为【" + maxWeight + "】\n当前重量为【" + blueWeight + "】\n请确认重量是否准确");
				filterDialog.show();
				filterDialog.getvCanncel().setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						filterDialog.dismiss();
						ScanOpen();
					}
				});
				filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						filterDialog.dismiss();
						//Add by wj过滤单号
						boolean isFilter= BillFilterUtil.isFilter(billNo,StoBagAndSendActivity.this);
						if(isFilter){
							showFilterDialog(billNo);
							return;
						}
						//End by wj
						if (addPieceRecord(billNo)) {
							setSaveData(true);
							// SoundManager.getInstance(this).playSuccessSound();
							Helper.showSoundAndVibrator(StoBagAndSendActivity.this, true);
							code.setSelection(code.length());
							addScanRecordInfo(billNo,weight.getText().toString());
							code.setText("");
						}
						// 提示插入数据失败
						else {
							Helper.showSoundToast(StoBagAndSendActivity.this, getString(R.string.code_repeat),
									false);
						}
						ScanOpen();
					}
				});
			}else {
				//Add by wj过滤单号
				boolean isFilter= BillFilterUtil.isFilter(billNo,this);
				if(isFilter){
					showFilterDialog(billNo);
					return;
				}
				//End by wj
				if (addPieceRecord(billNo)) {
					setSaveData(true);
					// SoundManager.getInstance(this).playSuccessSound();
					Helper.showSoundAndVibrator(this, true);
					code.setSelection(code.length());
					addScanRecordInfo(billNo);
					code.setText("");
				}
				// 提示插入数据失败
				else {
					Helper.showSoundToast(this, getString(R.string.code_repeat),
							false);
				}
				ScanOpen();
			}

		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	/**
	 * 检查车辆码规则
	 */
	private boolean checkCarId() {
		if (carID.getText().toString().length() > 0
				&& carID.length() != CARID_LENGTH) {
			Helper.showSoundToast(this,
					getString(R.string.car_id_median_error), false);
			carID.setText("");
			carID.requestFocus();
			return false;
		}
		if (carID.getText().toString().length() > 0
				&& !carID.getText().toString().matches("[0-9]+")) {
			Helper.showSoundToast(this, "车辆id非法", false);
			carID.setText("");
			carID.requestFocus();
			return false;
		}
		return true;
	}

	/**
	 * 检查包号是否正确
	 */
	private boolean checkBagCode() {
		if (bagCode.getText().length() <= 0) {
			Helper.showSoundToast(StoBagAndSendActivity.this, "包号不能为空!", false);
			bagCode.requestFocus();
			return false;
		}

		if (ScanRuleManager.getInstance(this).isBagCode(
				bagCode.getText().toString())) {
			code.requestFocus();
		} else {
			Helper.showSoundToast(StoBagAndSendActivity.this,
					getString(R.string.bag_code_error), false);
			bagCode.setText("");
			bagCode.requestFocus();
			return false;
		}

		return true;
	}

	// 增加一条记录
	private boolean addPieceRecord(String billNo) {
		boolean ret;
		if (bagCode.getText().toString().length() > 3) {

		} else {
			Helper.showSoundToast(this, "包号位数错误", false);
			bagCode.setText("");
			bagCode.requestFocus();
			return false;
		}
		dataBusiness.initInsertData();
		// 单号

		// 物品类别
		dataBusiness.setFunction_type(String.valueOf(itemType));
		// 车辆ID
		dataBusiness.setCarID_number(carID.getText().toString());
		// 下一站
		dataBusiness.setNext_station(nextStationCode);
		// 目的地
		dataBusiness.setUser_defined3(centerDesCode);
		// 包号
		dataBusiness.setBag_number(bagCode.getText().toString());
		// 蓝牙重量
		if (blueWeight > 0) {
			// 重量
			dataBusiness.setWeight(String.valueOf(blueWeight));
			blueWeight = -1;
		}
		// 路由
		if (routeCode.length() <= 0) {
			dataBusiness.setReason_number("");
		} else {
			dataBusiness.setReason_number(routeCode);
		}
		if (IS_24HOURS) {
			dataBusiness.setExpress_type("1");
		} else {
			dataBusiness.setExpress_type("");
		}

		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());

		// 插入包操作
		dataBusiness
				.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_PACKAGE_OPERATE
						.getOpCode());

		dataBusiness.setBar_code_number(bagCode.getText().toString());
		dataBusiness.setCodeType(getExpType(bagCode.getText().toString()));
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_AVIATION_PACKAGE_OPERATE);
		if (ret) {

			this.addCodeNumber();
		}

		// 扫描类型
		dataBusiness
				.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_PACKET_SEND
						.getOpCode());
		dataBusiness.setBar_code_number(billNo);
		dataBusiness.setCodeType(getExpType(billNo));
		// 插入装包记录
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_AVIATION_SCAN_PACKET_SEND);

		if (ret) {
			this.addCodeNumber();
		}


		return ret;
	}

	/**
	 * 通过路由号查找表 如果能查到数据，将下一站和二级中转目的地的数据显示在输入框中 注：路由表只能精确查询
	 */
	private void selectRoute(boolean isFocus) {
		try {
			routeCode = route.getText().toString();
			QueryRouteThread thread = new QueryRouteThread(isFocus);
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("selectRoute", e.getMessage());
		}
	}

	/*
	 * 监听控件
	 */
	@SuppressLint("NewApi")
	private void initListen() {
		goods.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View v) {
				itemType = 1;
				notgoods.setChecked(false);
			}
		});

		notgoods.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View v) {
				itemType = 2;
				goods.setChecked(false);
			}
		});
		route.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if(!TextUtils.isEmpty(nextStationCode)){
					nextStation.setText("");
					centerDes.setText("");
					nextStationCode="";
					routeCode="";
				}
			}
		});
		route.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
				//selectRoute(true); // 搜索路由数据
			}
		});
		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//Add by wj选择路由号
				selectRoute();
			}
		});
		carID.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				goods.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (checkCarId()) {
					bagCode.requestFocus();
				}
			}
		});
		bagCode.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				carID.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				if (checkBagCode()) {
					code.requestFocus();
				}
			}
		});
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				bagCode.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				codeProcess();
			}
		});

	}

	/**
	 * 单号逻辑处理判断
	 * 
	 * @author wxf
	 * 
	 */
	private void codeProcess() {
		String codeName = code.getText().toString();

		if (codeName.length() == 0) {
			Helper.showSoundToast(this, getString(R.string.code_empty), false);
		} else {
			// 如果扫描的单号是路由
			if (ROUTE_MIN_LENGTH <= codeName.length()
					&& codeName.length() <= ROUTE_MAX_LENGTH) {
				route.setText(codeName);
				selectRoute(false);
				code.setText("");
			} else {
				onScanResults(codeName);
				/*
				 * if (CheckScanCode(code.getText().toString())) {
				 * onScanResults(code.getText().toString()); } else {
				 * code.setText(""); }
				 */
			}
		}
	}

	@Override
	public void onBackPressed() {

		showNotice();
	}

	/**
	 * 扫描码判断
	 * 
	 * @param code
	 *            扫描码
	 * @return true/ok or false
	 */
	private boolean CheckScanCode(String code) {
		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code,
						EnumTableNames.STATUS_TABLE_AVIATION_SCAN_PACKET_SEND);
		if (status != EnumScanCode.CODE_WAY_BILL) {
			Helper.showSoundToast(this, status.message, false);
			return false;
		}
		return true;
	}
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if ((goods.isFocused() || notgoods.isFocused())
				&& keyCode == StoPdaKeyEvent.KEYCODE_DEL) {
			route.requestFocus();
		}
		return super.onKeyUp(keyCode, event);
	}

	/**
	 * 查询路由号信息线程
	 * 
	 * @author Administrator
	 * 
	 */
	class QueryRouteThread extends Thread {

		boolean isFocus = true;

		public QueryRouteThread(boolean isFocus) {
			// TODO Auto-generated constructor stub
			this.isFocus = isFocus;
		}

		@Override
		public void run() {
			super.run();
			final RouteEntity entity = RouteManager.getInstance(
					StoBagAndSendActivity.this).queryByRouteCode(routeCode);
			/**
			 * 查询下一站网点表，显示网点名称
			 */
			if (entity != null) {
				nextStationCode = entity.getNextStation();
				centerDesCode = entity.getCenterDes();
				if (entity.getNextStation().length() > 0) {
					nextStationName = SiteFullManager.getInstance(
							StoBagAndSendActivity.this).querySiteCodeName(
							nextStationCode);
				}
				if (entity.getCenterDes().length() > 0) {
					centerDesName = SiteFullManager.getInstance(
							StoBagAndSendActivity.this).querySiteCodeName(
							centerDesCode);
				}
			}
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (entity != null) {
						nextStation
								.setText((nextStationName.length() > 0) ? nextStationName
										: nextStationCode);
						centerDes
								.setText((centerDesName.length() > 0) ? centerDesName
										: centerDesCode);
						if (isFocus) {
							goods.requestFocus();
						}

					} else {
						route.setText("");
						routeCode = "";
						nextStationCode = "";
						nextStationName = "";
						nextStation.setText("");
						centerDesCode = "";
						centerDesName = "";
						centerDes.setText("");
						Helper.showSoundToast(StoBagAndSendActivity.this,
								"未定义，请到业务设置中更新数据", false);
					}
				}
			});
		}
	}

	@Override
	protected void handlerScanData(String scanData) {

		if(null!=filterDialog && filterDialog.isShowing()){
			return;
		}

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;

			// 如果扫描的单号是路由

			if (ROUTE_MIN_LENGTH <= result.length()
					&& result.length() <= ROUTE_MAX_LENGTH) {
				route.setText(result);
				selectRoute(true);
			}

			// 如果扫描的单号是车辆码
			else if (result.length() == CARID_LENGTH) {
				carID.setText(result);
			} // 包号
			else if (bagCode.hasFocus() &&  ScanRuleManager.getInstance(this).isBagCode(result)) {
				bagCode.setText(result);
				SoundManager.getInstance(StoBagAndSendActivity.this)
						.playSuccessSound();
				code.requestFocus();
			} else if (code.hasFocus()) {
				code.setText("");
				code.setText(result);
				code.setSelection(code.length());
				if (CheckScanCode(result)) {
					processScanData();
				}
				code.setText("");
			} else {
				Helper.showSoundToast(StoBagAndSendActivity.this, "错误条码!",
						false);
			}

		} else {
		}
	}

	//Add by wj

	/**
	 * 选择路由号
	 */
	private void selectRoute(){
		String routeStr=route.getText().toString().trim();
		Intent intent=new Intent(this,StoAviSelectRouteActivity.class);
		intent.putExtra("routeCode",routeStr);
		startActivityForResult(intent,0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode){
			case 0:

				if(data!=null){
					RouteEntity routeEntity=data.getParcelableExtra("route");
					route.setText(routeEntity.getRouteCode());
					selectRoute(true);
				}

				break;
		}
	}

	/**
	 * 蓝牙连接
	 *
	 * @author wxf
	 *
	 */
	private void bluetoothConnect() {
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				weight.setText(R.string.now_connect_blue);
				blueConnecting();
			} else {
				//weight.setText(R.string.blue_no_open);
			}
		} else {
//			promptDialog(getText(R.string.blue_not_available).toString());
		}
	}

	/**
	 * 蓝牙正式连接
	 */
	private void blueConnecting() {
		String macAddress = StoFilePreference.getInstance(this)
				.getBluetoothMacAddress();
		if (!macAddress.equals("")) {
			if (blueConnectThread != null) {
				blueConnectThread.cancelDialog();
				blueConnectThread.clearBlueDevices();
				blueConnectThread = null;
			}
//			weight.setEnabled(false);
			blueConnectThread = new BlueReadThread(this,
					bluetoothHandler, macAddress, false);
			blueConnectThread.start();
		} else {
			weight.setText(R.string.select_blue_scales);
		}
	}

	private Handler bluetoothHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.d("logdebug:", "msg.what:" + msg.what);
			if (msg.what == BlueWeigthManager.UPDATE_BLUE_DATA) {
				if (blueConnectThread != null) {
					blueConnectThread.cancelDialog();
				}
				if (msg.obj != null && !msg.obj.toString().equals("")) {
					String result = msg.obj.toString();
					Log.d("msg=", String.valueOf(result));
					// 表示连接蓝牙失败
					if (result.equals(BlueWeigthManager.CONNECT_FAIL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							if(blueConnCount < 3){
								blueConnecting();
								blueConnCount++;
								weight.setText(
										getText(R.string.blue_connect_fail).toString() + ",正在重连" + blueConnCount + "...");
							}else{
								blueConnCount = 0;
								weight.setText(
										getText(R.string.blue_connect_fail).toString() + ",请到系统设置, 重新设置蓝牙!");
							}
						}
					}
					// 没有选择秤型号
					else if (result
							.equals(BlueWeigthManager.NO_SELECT_SCALE_MODEL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(
									getText(R.string.no_select_scales_model).toString() + "请到系统设置,设置蓝牙!");

						}

					}
					// 读取数据失败
					else if (result.equals(BlueWeigthManager.READ_ERROR)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(
									R.string.get_data_error);
						}
					} else {
						// 显示重量
						blueWeight = parseFloat(result);
						weight.setText(result);
					}
				}
			}
		}

	};
}
